import 'dart:convert';
import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_trip/Model/CityModel.dart';
import 'package:lpinyin/lpinyin.dart';

class CityListPage extends StatefulWidget {
  /// 当前的城市
  String _cityName;
  CityListPage(this._cityName);

  @override
  _CityListPageState createState() => _CityListPageState();
}

class _CityListPageState extends State<CityListPage> {
  /// 城市列表数组
  List<CityModel> _cityList;

  /// 当前分组索引
  String _suspensionTag;

  /// 悬浮组头高度
  final int _suspensionHeight = 50;

  /// 每个item高度
  final int _itemHeight = 44;

  @override
  void initState() {
    super.initState();
    _loadCityListFromJson();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: _appBar,
        body: Column(children: <Widget>[_locationWidget, _listView]));
  }

  /// 导航栏
  Widget get _appBar {
    return AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(widget._cityName),
        ),
        title: Text('城市选择', style: TextStyle(color: Colors.white)));
  }

  /// 当前城市widget
  Widget get _locationWidget {
    return Container(
        decoration: BoxDecoration(
            border: Border(
                bottom:
                    BorderSide(color: Colors.grey.withAlpha(100), width: 0.5))),
        child: ListTile(
            title: Text('当前所选城市'),
            trailing: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
              Icon(Icons.location_on),
              Text(widget._cityName),
            ])));
  }

  /// 构建listView
  Widget get _listView {
    return Expanded(
        child: AzListView(
      header: _header,
      data: _cityList ?? [],
      itemBuilder: (context, cityModel) =>
          _buildListItem(context: context, cityModel: cityModel),
      itemHeight: _itemHeight,
      isUseRealIndex: true,
      onSusTagChanged: (alphaIndex) {
        setState(() {
          _suspensionTag = alphaIndex;
        });
      },
      suspensionWidget: _buildSusWidget(_suspensionTag),
      suspensionHeight: _suspensionHeight,
    ));
  }

  /// 构建列表 item Widget
  Widget _buildListItem(
      {@required BuildContext context, @required CityModel cityModel}) {
    return Column(children: <Widget>[
      Offstage(
          // 隐藏组件 offstage=true 会进行隐藏
          offstage: !cityModel.isShowSuspension,
          child: Container(
              height: _suspensionHeight.toDouble(),
              child: _buildSusWidget(cityModel.alphaIndex))),
      SizedBox(
          height: _itemHeight.toDouble(), // 一定要限定高度 这样点击索引时才会跳转到正确的位置
          child: GestureDetector(
            onTap: () => Navigator.of(context).pop(cityModel.name),
            child: ListTile(title: Text(cityModel.name)),
          ))
    ]);
  }

  /// 构建悬停Widget.
  Widget _buildSusWidget(String alphaIndex) {
    return Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 20.0),
        height: _suspensionHeight.toDouble(), // 一定要加上高度
        color: Color(0xfff3f4f5),
        child: Text(alphaIndex ?? '',
            style: TextStyle(color: Colors.blue, fontSize: 25)));
  }

  /// listView头部视图
  AzListViewHeader get _header {
    List<CityModel> hotCityList = List();
    hotCityList.addAll([
      CityModel(name: "北京市"),
      CityModel(name: "上海市"),
      CityModel(name: "广州市"),
      CityModel(name: "深圳市"),
      CityModel(name: "杭州市"),
      CityModel(name: "成都市"),
      CityModel(name: "武汉市"),
      CityModel(name: "苏州市"),
    ]);
    List<OutlineButton> buttonList = hotCityList.map((cityModel) {
      return OutlineButton(
          onPressed: () => Navigator.of(context).pop(cityModel.name),
          child: Text(cityModel.name));
    }).toList();
    return AzListViewHeader(
        tag: '热门',
        height: 120,
        builder: (context) {
          return Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: buttonList.sublist(0, 4)),
                Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: buttonList.sublist(4, buttonList.length))
              ]);
        });
  }

  /// 从本地文件加载城市列表
  void _loadCityListFromJson() async {
    String jsonStr = await rootBundle.loadString('resources/cities.json');
    List list = json.decode(jsonStr);
    if (list == null || list.isEmpty) return;
    List<CityModel> cityList =
        list.map((json) => CityModel.fromJson(json)).toList();

    for (CityModel cityModel in cityList) {
      String pinyin = PinyinHelper.getPinyinE(cityModel.name);
      String alphaIndex = pinyin.substring(0, 1).toUpperCase();
      cityModel.pinyin = pinyin;
      if (RegExp('[A-Z]').hasMatch(alphaIndex)) {
        cityModel.alphaIndex = alphaIndex;
      } else {
        cityModel.alphaIndex = '#';
      }
    }

    // 根据A-Z排序
    SuspensionUtil.sortListBySuspensionTag(cityList);

    setState(() {
      _cityList = cityList;
    });
  }
}
